<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import { useGetOrgSealCreateUrl } from '@fl/api/supplier'
import { SubmitBtn } from '@fl/components'

// 1公司章  2法人章
const props = withDefaults(defineProps<{
    type?: number
    redirectUrl?: string
}>(), {
    type: 1,
    redirectUrl: '',
})

const formData = ref({
    sealName: '',
})

const formRef = ref()
const { type, redirectUrl } = toRefs(props)

const title = computed(() => {
    return type.value === 1
        ? '新增公司章'
        : '新增法人章'
})

const { isPending, mutate } = useGetOrgSealCreateUrl()

const visible = defineModel<boolean>('visible', { required: true })

const columns: PlusColumn[] = [
    {
        label: '印章名称',
        prop: 'sealName',
        width: 120,
        fieldProps: {
            maxlength: 50,
        },
    },
]

const rules = {
    sealName: [
        {
            required: true,
            validator: validateSealName,
        },
    ],
}

function validateSealName(rule, value, callback) {
    const pattern = /^[\u4E00-\u9FA5a-zA-Z0-9\uFF08\uFF09\uFF0E\u3007\u3000\u0020\uFF0D-]{2,50}$/u
    if (!value) {
        callback(new Error('请输入印章名称'))
    }
    if (value.length < 2 || value.length > 50) {
        callback(new Error('印章名称长度需为2~50个字符'))
    }
    if (pattern.test(value))
        callback()
    else
        callback(new Error('仅支持：数字、中文、英文大小写、“（）”、“·”、“空格”、“-”，全角和半角'))
}

async function confirm() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const params = {
            ...formData.value,
            sealType: type.value,
            redirectUrl: redirectUrl.value,
        }
        visible.value = false
        mutate(params, {
            onSuccess: (res) => {
                if (res)
                    window.open(res, '_self')
            },
        })
    }
}

function cancel() {
    visible.value = false
}

function reset() {
    formRef.value.formInstance.resetFields()
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="500"
                close-on-press-escape
                @cancel="cancel"
                @closed="reset"
    >
        <PlusForm ref="formRef"
                  v-model="formData"
                  :columns="columns"
                  :label-width="100"
                  :rules="rules"
                  :has-footer="false"
        />

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
